package com.cos.shop.web.filter;

import com.cos.shop.common.Const;
import com.cos.shop.entity.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebFilter(filterName = "Filter03_LoginRull",value = "/*")
public class Filter03_LoginRull implements Filter {
    @Override
    public void destroy() {
    }
    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response= (HttpServletResponse) resp;

        String uri = request.getRequestURI();

        if (checkLogin(uri)) {
            User user = (User) request.getSession().getAttribute(Const.SystemConst.IS_LOGIN);
            if (user == null) {
                response.sendRedirect(request.getContextPath()+"/login.jsp");
                return;
            }else{
                chain.doFilter(request, response);
            }
        }else{
            chain.doFilter(request, response);
        }

    }

    public boolean checkLogin(String uri){
        List<String> list = new ArrayList<>();
        list.add("cart");
        list.add("address");
        list.add("orders");
        for (String s : list) {
            if (uri.contains(s)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void init(FilterConfig config) throws ServletException {

    }

}
